package org.lhq.goldenplugin.service

import com.intellij.notification.NotificationGroupManager
import com.intellij.notification.NotificationType
import com.intellij.openapi.components.Service
import com.intellij.openapi.diagnostic.logger
import org.lhq.goldenplugin.entity.GoldenTrade
import org.lhq.goldenplugin.i18n.GoldenBundle
import org.lhq.goldenplugin.utils.GsonUtils
import org.lhq.goldenplugin.utils.OkHttpClient

@Service(Service.Level.PROJECT)
class PriceService {
    private val logger = logger<PriceService>()
    
    // 默认阈值设为0表示不启用提醒功能
    var goldPriceThreshold: Double = 900.0
    private var hasNotified: Boolean = false
    private var lastNotifiedPrice: Double = 0.0

    fun fetchPrice(): GoldenTrade? {
        val client = OkHttpClient.client
        val request = okhttp3.Request.Builder()
            .url("https://free.xwteam.cn/api/gold/trade")
            .build()
        val response = client.newCall(request).execute()
        var goldenEntity: GoldenTrade? = null
        if (response.isSuccessful) {
            val bodyStr = response.body.string()
            goldenEntity = GsonUtils.fromJson(bodyStr, GoldenTrade::class.java)
            // 检查阈值
            checkThreshold(goldenEntity)
        } else {
            logger.warn("Failed to fetch gold price data. Response code: ${response.code}")
        }
        return goldenEntity
    }
    
    private fun checkThreshold(trade: GoldenTrade?) {
        if (goldPriceThreshold <= 0) return // 阈值未设置则不检查
        
        trade?.data?.sh?.find { it.symbol == "SH_Au9999" }?.let { goldItem ->
            val currentPrice = goldItem.bp
            val title = GoldenBundle.message("notification.title")
            // 当价格达到或超过阈值且尚未通知时发送提醒
            if (currentPrice >= goldPriceThreshold && !hasNotified) {
                showNotification(
                    title,
                    "黄金价格已达到或超过设定阈值！\n当前价格: $currentPrice\n设定阈值: $goldPriceThreshold"
                )
                hasNotified = true
                lastNotifiedPrice = currentPrice
                logger.info("Gold price alert triggered at price: $currentPrice, threshold: $goldPriceThreshold")
            }
            // 当已通知过且回落到阈值以下时重置通知状态
            else if (hasNotified && currentPrice < goldPriceThreshold) {
                hasNotified = false
                logger.info("Gold price alert reset as price dropped below threshold: $currentPrice")
            }
        }
    }
    
    private fun showNotification(title: String, content: String) {
        val notificationGroup = NotificationGroupManager.getInstance()
            .getNotificationGroup("Gold Price Notification")
        
        notificationGroup.createNotification(title, content, NotificationType.INFORMATION)
            .notify(null)
    }
    
    // 重置通知状态，允许再次通知
    fun resetNotification() {
        hasNotified = false
        lastNotifiedPrice = 0.0
    }
    
    // 获取上次通知时的价格
    fun getLastNotifiedPrice(): Double = lastNotifiedPrice
}